/*******************************************************************************
 *  Copyright (c) 2010 Chase Technology Ltd.
 *  
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the GNU General Public License v3.0
 *  which is available at http://www.gnu.org/licenses/
 * 
 * Contributors:
 *     Doug Satchwell - initial API and implementation
 *******************************************************************************/
package org.jfunction.internal.parser;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
import org.jfunction.JFunctionFile;

/**
 * Parser for the scenario sections of a scenario file
 * 
 * @author Doug Satchwell
 */
public class ScenarioParser extends AbstractParser {

	public ScenarioParser(KeyWords keywords) {
		super(new ScenarioScanner(keywords));
	}
	
	private String getTokenText() throws BadLocationException {
		return document.get(scanner.getTokenOffset(),scanner.getTokenLength());
	}

	protected void doParse(JFunctionFile jf) throws BadLocationException {
		IToken token;
		StringBuilder currentText = new StringBuilder();
		boolean stepFound = false;
		while ((token = scanner.nextToken()) != Token.EOF) {
			System.out.println(token);
			System.out.println(document.get(scanner.getTokenOffset(),scanner.getTokenLength()));
			if (token instanceof JFunctionToken) {
				JFunctionToken stoken = (JFunctionToken) token;
				switch (stoken) {
					case SCENARIO:
						// do nothing
						break;
					case COMMENT:
					case STEP: 
						if (currentText.length() > 0) {
							if (stepFound)
								jf.addStep(currentText.toString());
							else
								jf.setScenarioDescription(currentText.toString());
							currentText.setLength(0);
						}
						stepFound = true;
						break;
					case FIELD:
						currentText.append(getTokenText());
				}
			} else {
				currentText.append(getTokenText());
			}
		}
		if (currentText.length() > 0) {
			if (stepFound)
				jf.addStep(currentText.toString());
			else
				jf.setScenarioDescription(currentText.toString());
		}
	}
}
